package com.chzc.server;

import com.chzc.entity.DevilMessage;
import com.chzc.initializer.DevilConsumerInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.StandardCharsets;


/**
 * 消息发送者
 */
public class DevilConsumer {

    /**
     * broker地址
     */
    private final String host;

    /**
     * broker端口号
     */
    private final int port;


    /**
     * 队列名
     */
    private final String queueName;

    private Bootstrap bootstrap;


    public DevilConsumer(String host, int port, String queueName) {
        this.host = host;
        this.port = port;
        this.queueName = queueName;
    }

    private ChannelFuture channelFuture;

    private EventLoopGroup group;

    /**
     * 消息发送者建立连接
     */
    public void start(SimpleChannelInboundHandler<DevilMessage> channelInboundHandler) {
        group = new NioEventLoopGroup();
        try {
            bootstrap = new Bootstrap();
            //自定义一个初始化类
            bootstrap.group(group).channel(NioSocketChannel.class)
                    .handler(new DevilConsumerInitializer(channelInboundHandler));
            this.channelFuture = bootstrap.connect(this.host, this.port).sync();
            DevilMessage devilMessage = new DevilMessage(
                    // 占位符，也用于加密信道
                    1, "1".getBytes(StandardCharsets.UTF_8),
                    // 占位符
                    1, "1".getBytes(StandardCharsets.UTF_8),
                    queueName.getBytes(StandardCharsets.UTF_8),
                    queueName.getBytes(StandardCharsets.UTF_8).length,
                    2,
                    false);
            channelFuture.channel().writeAndFlush(devilMessage);
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
